//
//  RegisterViewController.swift
//  Preferential
//
//  Created by Fineland on 2021/3/17.
//

import UIKit

class RegisterViewController: UITableViewController {
    
    //用户名、密码
    private var userTextField: UITextField!
    private var passwordTextField: UITextField!
    private var password2TextField: UITextField!
    //操作按钮
    private var nextButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "注册"
        
        //自定义返回按钮样式
        self.leftItem()
        //创建视图
        initViews()
        
        
        
    }
    
    // MARK: - Custom Methods
    
    private func initViews() -> Void {
        
        //修改tableView样式
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor.white
        //tableView的headerView
        thView()
        //tableView的footerView
        tfView()
    }
    
    private func thView() -> Void {
        
        //说明
        let infoLabel = UILabel(frame: CGRect(x: NSKVar.kLR20, y: 0.0, width: NSKVar.kScreenWidth - 2.0 * NSKVar.kLR20,
                                              height: 124.0))
        infoLabel.font = UIFont.systemFont(ofSize: 22.0)
        infoLabel.numberOfLines = 0
        infoLabel.text = "你好，" + "\n" + "欢迎注册优惠购"
        //用户名
        let hTextField: CGFloat = 54.0
        userTextField = textField(with: CGRect(x: NSKVar.kLR20, y: infoLabel.frame.maxY, width: infoLabel.frame.size.width,
                                               height: hTextField),
                                  placeholder: "请输入您的手机号", keyboardType: .numberPad)
        //分隔线
        let lineLayer = CALayer()
        lineLayer.frame = CGRect(x: NSKVar.kLR20, y: userTextField.frame.maxY, width: infoLabel.frame.size.width,
                                 height: 0.5)
        lineLayer.backgroundColor = NSKVar.SEPERATOR_COLOR.cgColor
        //密码
        passwordTextField = textField(with: CGRect(x: NSKVar.kLR20, y: lineLayer.frame.maxY,
                                                   width: infoLabel.frame.size.width,
                                                   height: hTextField),
                                      placeholder: "设置8~16位密码", isSecure: true)
        //确认密码
        password2TextField = textField(with: CGRect(x: NSKVar.kLR20, y: passwordTextField.frame.maxY,
                                                  width: infoLabel.frame.size.width,
                                                  height: hTextField),
                                       placeholder: "请确认您的登录密码", isSecure: true, returnKeyType: .go)
        //tableView的headerView
        let tbhView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: NSKVar.kScreenWidth, height: password2TextField.frame.maxY))
        //添加
        tbhView.addSubview(infoLabel)
        tbhView.addSubview(passwordTextField)
        tbhView.addSubview(userTextField)
        tbhView.addSubview(password2TextField)
        //标题
        userTitle()
        passwordTitle("设置密码", to: passwordTextField)
        passwordTitle("确认密码", to: password2TextField)
        //设置
        self.tableView.tableHeaderView = tbhView
    }
    
    private func userTitle() -> Void {
        
        let hVal: CGFloat = 0.4 * userTextField.frame.size.height
        //手机区号
        let wLabel: CGFloat = 84.0
        let zoneLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: wLabel, height: hVal))
        zoneLabel.font = userTextField.font
        zoneLabel.attributedText = userAttrText()
        //分隔线
        let lineLayer = CALayer()
        lineLayer.frame = CGRect(x: zoneLabel.frame.maxX, y: 0.0, width: 1.0, height: hVal)
        lineLayer.backgroundColor = NSKVar.SEPERATOR_COLOR.cgColor
        //用户名称标题视图
        let wVal: CGFloat = 104.0
        let tempView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: wVal, height: hVal))
        //添加
        tempView.addSubview(zoneLabel)
        tempView.layer.addSublayer(lineLayer)
        //设置
        userTextField.leftView = tempView
        userTextField.leftViewMode = .always
    }
    
    private func passwordTitle(_ title: String, to textField: UITextField) -> Void {
        
        let hVal: CGFloat = 0.4 * userTextField.frame.size.height
        //手机区号
        let wLabel: CGFloat = 84.0
        let zoneLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: wLabel, height: hVal))
        zoneLabel.font = userTextField.font
        zoneLabel.text = title
        //用户名称标题视图
        let wVal: CGFloat = 104.0
        let tempView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: wVal, height: hVal))
        //添加
        tempView.addSubview(zoneLabel)
        //设置
        textField.leftView = tempView
        textField.leftViewMode = .always
    }
    
    private func tfView() -> Void {
        
        //按钮
        let hButton: CGFloat = 50.0
        nextButton = "注册".button(with: CGRect(x: NSKVar.kLR20, y: 3.0 * NSKVar.kLR15, width: userTextField.frame.size.width,
                                                  height: hButton),
                                     target: self, action: #selector(nextButtonTouched(_:)))
        //tableView的footView
        let tbfView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: NSKVar.kScreenWidth, height: nextButton.frame.maxY))
        //添加
        tbfView.addSubview(nextButton)
        //设置
        self.tableView.tableFooterView = tbfView
    }
    
    @objc private func nextButtonTouched(_ sender: UIButton) -> Void {
        
        //关闭键盘
        self.tableView.endEditing(false)
        //用户名是否为空？
        let accountVal = userTextField.text ?? ""
        if "" == accountVal {
            UIKToastView.showText("请输入您的手机号码")
            return
        }
        if true != accountVal.regularPhone() {
            UIKToastView.showText("请输入正确的手机号码")
            return
        }
        //密码是否为空？
        let passwordVal = passwordTextField.text ?? ""
        if "" == passwordVal {
            UIKToastView.showText("请设置您的密码")
            return
        }
        //长度是否符合要求？
        let passwordLength = passwordVal.count
        if passwordLength < 8 || passwordLength > 16 {
            UIKToastView.showText("密码长度要求8~16位")
            return
        }
        //确认密码是否为空？
        let password2Val = password2TextField.text ?? ""
        if "" == password2Val {
            UIKToastView.showText("请确认密码")
            return
        }
        //两次密码是否一致？
        if passwordVal != password2Val {
            UIKToastView.showText("两次密码不致，请确认")
            return
        }
        //请求
        registerRequest()
    }
    
    @objc private func endOnExit(_ sender: UITextField) -> Void {
        
        //关闭键盘
        sender.resignFirstResponder()
        //是否为确认密码？
        if sender.isEqual(password2TextField) {
            registerRequest()
        }
    }
    
    private func userAttrText() -> NSAttributedString {
        
        //图片大小
        let szImg = CGSize(width: 10.0, height: 10.0)
        let attachment = NSTextAttachment()
        attachment.bounds = CGRect(origin: CGPoint(x: 0.0, y: -1.0), size: szImg)
        attachment.image = UIImage(named: "system_arrow_down_gray")
        //值
        let tempVal = NSMutableAttributedString(attributedString: NSAttributedString(string: "+86  "))
        tempVal.append(NSAttributedString(attachment: attachment))
        //返回
        return tempVal
    }
    
    private func textField(with frame: CGRect, placeholder: String,
                           isSecure: Bool = false, keyboardType: UIKeyboardType = .default,
                           returnKeyType: UIReturnKeyType = .done) -> UITextField {
        
        //创建
        let tempTextField = UITextField(frame: frame)
        tempTextField.borderStyle = .none
        tempTextField.font = UIFont.systemFont(ofSize: 16.0)
        tempTextField.placeholder = placeholder
        tempTextField.isSecureTextEntry = isSecure
        tempTextField.clearButtonMode = .whileEditing
        tempTextField.keyboardType = keyboardType
        tempTextField.returnKeyType = returnKeyType
        tempTextField.addTarget(self, action: #selector(endOnExit(_:)), for: .editingDidEndOnExit)
        //分隔线
        let lineLayer = CALayer()
        lineLayer.frame = CGRect(x: 0.0, y: frame.size.height, width: frame.size.width, height: 0.5)
        lineLayer.backgroundColor = NSKVar.SEPERATOR_COLOR.cgColor
        //添加
        tempTextField.layer.addSublayer(lineLayer)
        //返回
        return tempTextField
    }
    
    private func registerRequest() -> Void {
        
        //成功
        UIKToastView.showText("注册成功，请登录") { [weak self] (finished: Bool) in
            self?.close()
        }
        //请求参数
//        let paramObj = ["account": userTextField.text!, "password": password2TextField.text!] as [String: Any]
//        //请求对象
//        self.requestObj.requestTarget(NSKMoyaAPI.register(params: paramObj), with: { [weak self] (resObj: Any?) in
//            //成功
//            UIKToastView.showText("注册成功，请登录") { [weak self] (finished: Bool) in
//                self?.close()
//            }
//            
//        }) { [unowned self] (cde: NSKResponseCode, msg: String) in
//            //隐藏等待
////            self.showWaitting(false)
//        }
    }
}
